package com.awonsome.oss.context;

import com.aliyun.oss.OSS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;

import java.util.Map;

/**
 * 当 ApplicationContext 关闭 ApplicationListener 时，关闭所有 OSS 客户端。
 *
 * @author yangdejun
 * @date 2022/1/5 23:05
 */
public class OssApplicationListener implements ApplicationListener<ContextClosedEvent> {

    private static final Logger log = LoggerFactory.getLogger(OssApplicationListener.class);

    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        Map<String, OSS> ossClientMap = event.getApplicationContext()
                .getBeansOfType(OSS.class);
        log.info("{} OSSClients will be shutdown soon", ossClientMap.size());
        ossClientMap.keySet().forEach(beanName -> {
            log.info("shutdown ossClient: {}", beanName);
            ossClientMap.get(beanName).shutdown();
        });
    }
}
